#pragma once
#include <iostream>
#include <fstream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unordered_map>
#include "log.hpp"
#include "inetaddr.hpp"

using namespace myaddr;
using namespace mylog;

namespace mydict
{
    const static std::string default_dict = "./dict.txt";
    const static std::string sep = " : ";
    class Dict
    {
    public:
        Dict(const std::string &path = default_dict)
            : _dictpath(path)
        {
        }
        ~Dict()
        {
        }
        void Load()
        {
            // 打开文件
            std::fstream in(_dictpath);
            if (!in.is_open())
            {
                LOG(Level::FATAL) << "file open error";
                exit(1);
            }
            std::string line;
            while (std::getline(in, line))
            {
                auto pos = line.find(sep);
                if (pos == std::string::npos)
                {
                    LOG(Level::WARNING) << "翻译错误 :" << line;
                    continue;
                }
                std::string english = line.substr(0, pos);
                std::string chinese = line.substr(pos + sep.size());
                if (english.empty() || chinese.empty())
                {
                    LOG(Level::WARNING) << "错误信息 : " << english << "->" << chinese;
                    continue;
                }
                _dict.insert(std::make_pair(english, chinese));
                LOG(Level::DEBUG) << english << "->" << chinese;
            }
            // 读取
        }
        std::string Translate(const std::string &word, const Addr &addr)
        {
            if (_dict.count(word) == 0)
            {
                return "unknow";
            }
            std::string chinese = _dict[word];
            LOG(Level::DEBUG) << "[" << addr.GetString() << "]  : " << word << "->" << chinese;
            return chinese;
        }

    private:
        std::string _dictpath;
        std::unordered_map<std::string, std::string> _dict;
    };

}